package org.example.env_boot.service;

import org.example.env_boot.dto.ApiResponse;
import org.example.env_boot.entity.AqiFeedback;
import org.example.env_boot.entity.GridMember;
import org.example.env_boot.entity.Statistics;
import org.example.env_boot.repository.AqiFeedbackRepository;
import org.example.env_boot.repository.GridMemberRepository;
import org.example.env_boot.repository.StatisticsRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * 网格员服务类
 */
@Service
public class GridMemberService {
    
    private final AqiFeedbackRepository feedbackRepository;
    private final GridMemberRepository gridMemberRepository;
    private final StatisticsRepository statisticsRepository;
    
    public GridMemberService(AqiFeedbackRepository feedbackRepository,
                            GridMemberRepository gridMemberRepository,
                            StatisticsRepository statisticsRepository) {
        this.feedbackRepository = feedbackRepository;
        this.gridMemberRepository = gridMemberRepository;
        this.statisticsRepository = statisticsRepository;
    }
    
    /**
     * 获取分配给网格员的反馈信息
     */
    public ApiResponse<List<AqiFeedback>> getAssignedFeedbacks(Integer gmId) {
        // 验证网格员是否存在
        Optional<GridMember> gridMemberOpt = gridMemberRepository.findById(gmId);
        if (gridMemberOpt.isEmpty()) {
            return ApiResponse.error("网格员不存在");
        }
        
        // 查找分配给该网格员且状态为已指派(1)的反馈信息
        List<AqiFeedback> feedbacks = feedbackRepository.findByGmIdAndState(gmId, 1);
        return ApiResponse.success("获取分配反馈信息成功", feedbacks);
    }
    
    /**
     * 获取网格员处理过的所有反馈信息
     */
    public ApiResponse<List<AqiFeedback>> getProcessedFeedbacks(Integer gmId) {
        // 验证网格员是否存在
        Optional<GridMember> gridMemberOpt = gridMemberRepository.findById(gmId);
        if (gridMemberOpt.isEmpty()) {
            return ApiResponse.error("网格员不存在");
        }
        
        List<AqiFeedback> feedbacks = feedbackRepository.findByGmId(gmId);
        return ApiResponse.success("获取处理过的反馈信息成功", feedbacks);
    }
    
    /**
     * 确认AQI数据并生成统计记录
     */
    public ApiResponse<Statistics> confirmAQIData(Integer gmId, Integer feedbackId, 
                                                  Integer so2Value, Integer coValue, Integer spmValue, Integer aqiId) {
        // 验证网格员是否存在
        Optional<GridMember> gridMemberOpt = gridMemberRepository.findById(gmId);
        if (gridMemberOpt.isEmpty()) {
            return ApiResponse.error("网格员不存在");
        }
        
        // 验证反馈信息是否存在且分配给该网格员
        Optional<AqiFeedback> feedbackOpt = feedbackRepository.findById(feedbackId);
        if (feedbackOpt.isEmpty()) {
            return ApiResponse.error("反馈信息不存在");
        }
        
        AqiFeedback feedback = feedbackOpt.get();
        if (!feedback.getGmId().equals(gmId)) {
            return ApiResponse.forbidden("此反馈信息未分配给您");
        }
        
        if (feedback.getState() != 1) {
            return ApiResponse.error("反馈信息状态错误，无法确认");
        }
        
        // 创建统计记录
        Statistics statistics = new Statistics();
        statistics.setFeedbackId(feedbackId);
        statistics.setGmId(gmId);
        statistics.setProvinceId(feedback.getProvinceId());
        statistics.setCityId(feedback.getCityId());
        statistics.setAqiId(aqiId);
        statistics.setSo2Density(so2Value);
        statistics.setCoDensity(coValue);
        statistics.setSpmDensity(spmValue);
        
        // 设置统计时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        statistics.setDateTime(now.format(dateTimeFormatter));
        
        // 保存统计记录
        Statistics savedStatistics = statisticsRepository.save(statistics);
        
        // 更新反馈信息状态为已确认(2)
        feedback.setState(2);
        feedbackRepository.save(feedback);
        
        return ApiResponse.success("AQI数据确认成功", savedStatistics);
    }
    
    /**
     * 获取网格员的工作统计
     */
    public ApiResponse<WorkStatistics> getWorkStatistics(Integer gmId) {
        // 验证网格员是否存在
        Optional<GridMember> gridMemberOpt = gridMemberRepository.findById(gmId);
        if (gridMemberOpt.isEmpty()) {
            return ApiResponse.error("网格员不存在");
        }
        
        Long totalAssigned = feedbackRepository.countByGmId(gmId);
        Long pendingCount = feedbackRepository.findByGmId(gmId).stream()
                .mapToLong(feedback -> feedback.getState() == 1 ? 1 : 0)
                .sum();
        Long completedCount = feedbackRepository.findByGmId(gmId).stream()
                .mapToLong(feedback -> feedback.getState() == 2 ? 1 : 0)
                .sum();
        
        WorkStatistics statistics = new WorkStatistics();
        statistics.setTotalAssigned(totalAssigned);
        statistics.setPendingCount(pendingCount);
        statistics.setCompletedCount(completedCount);
        
        return ApiResponse.success("获取工作统计成功", statistics);
    }
    
    /**
     * 根据反馈ID获取详细信息
     */
    public ApiResponse<AqiFeedback> getFeedbackDetail(Integer gmId, Integer feedbackId) {
        Optional<AqiFeedback> feedbackOpt = feedbackRepository.findById(feedbackId);
        if (feedbackOpt.isEmpty()) {
            return ApiResponse.error("反馈信息不存在");
        }
        
        AqiFeedback feedback = feedbackOpt.get();
        if (!feedback.getGmId().equals(gmId)) {
            return ApiResponse.forbidden("无权查看此反馈信息");
        }
        
        return ApiResponse.success("获取反馈详情成功", feedback);
    }
    
    /**
     * 工作统计信息类
     */
    public static class WorkStatistics {
        private Long totalAssigned;    // 总分配数
        private Long pendingCount;     // 待处理数
        private Long completedCount;   // 已完成数
        
        public Long getTotalAssigned() { return totalAssigned; }
        public void setTotalAssigned(Long totalAssigned) { this.totalAssigned = totalAssigned; }
        public Long getPendingCount() { return pendingCount; }
        public void setPendingCount(Long pendingCount) { this.pendingCount = pendingCount; }
        public Long getCompletedCount() { return completedCount; }
        public void setCompletedCount(Long completedCount) { this.completedCount = completedCount; }
    }
} 